package bfsalgorithm;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 1162. 地图分析
 */
public class Exercise11 {
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};
    public int maxDistance(int[][] grid) {
        int m = grid.length,n = grid[0].length;
        boolean[][] visit = new boolean[m][n];
        int[][] height = new int[m][n];
        Queue<int[]> q = new LinkedList<>();
        for(int i = 0;i < m;i++) {
            for(int j = 0;j < n ;j++) {
                if(grid[i][j] == 1) {
                    q.add(new int[]{i,j});
                    height[i][j] = 0;
                    visit[i][j] = true;
                }
            }
        }
        int ret = -1; // 因为可能返回-1
        while(!q.isEmpty()) {
            int size = q.size();
            while(size-- != 0) {
                int[] tmp = q.poll();
                int a = tmp[0],b = tmp[1];
                for(int k = 0;k < 4;k++) {
                    int x = a + dx[k];
                    int y = b + dy[k];
                    if(x >= 0 && x < m && y >= 0 && y < n && !visit[x][y]) {
                        height[x][y] = height[a][b] + 1;
                        q.add(new int[]{x,y});
                        visit[x][y] = true;
                        ret = Math.max(ret,height[x][y]);
                    }
                }
            }
        }
        return ret;
    }
}
